﻿using Microsoft.Data.Sqlite;
using SqlSugar;
using System.Reflection;

namespace WorkTool2.Helpers;

public class SqlSugarHelper
{
    public static readonly string dbName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources", "WorkToolDB.db");

    private static readonly string connString = new SqliteConnectionStringBuilder()
    {
        DataSource = dbName,
        Mode = SqliteOpenMode.ReadWriteCreate,
        Password = "wkadmin#shu"
    }.ToString();

    public static SqlSugarClient SqliteDb = new(new ConnectionConfig()
    {
        ConnectionString = connString,//获取加密后的字符串
        DbType = DbType.Sqlite,//数据库类型
        IsAutoCloseConnection = false,//关闭自动释放
        ConfigureExternalServices = new ConfigureExternalServices
        {
            EntityService = (c, p) =>
            {
                if (p.IsPrimarykey == false && new NullabilityInfoContext()
                 .Create(c).WriteState is NullabilityState.Nullable)
                {
                    p.IsNullable = true;
                }
            }
        },
        MoreSettings = new ConnMoreSettings()
        {
            EnableCodeFirstUpdatePrecision = true,
            SqliteCodeFirstEnableDropColumn = true
        }
    }, db =>
    {
    });

    public void SqlSugarClient(string connStr, DbType dbType, Action<SqlSugarClient> callback)
    {
        var sqlSugarClient = new SqlSugarClient(new ConnectionConfig()
        {
            DbType = dbType,
            ConnectionString = connStr,
            IsAutoCloseConnection = true,
            ConfigureExternalServices = new ConfigureExternalServices
            {
                EntityService = (c, p) =>
                {
                    if (p.IsPrimarykey == false && new NullabilityInfoContext()
                     .Create(c).WriteState is NullabilityState.Nullable)
                    {
                        p.IsNullable = true;
                    }
                }
            },
            MoreSettings = new ConnMoreSettings()
            {
                EnableCodeFirstUpdatePrecision = true,
                SqliteCodeFirstEnableDropColumn = true
            }
        });
        callback(sqlSugarClient);
    }
}